package com.scr1pt.fileshare2.utils

import com.scr1pt.extension.isNotNullOrBlank
import com.scr1pt.extension.isNullOrBlank
import javax.servlet.http.HttpServletRequest

/**
 * 说明: TODO
 *
 * 创建者: tum0r
 *
 * 时间: 2022/2/4 15:04
 */
fun String?.handlePath(): String {
    var result = this ?: ""
    if (!result.startsWith("/")) result = "/$result"
    if (!result.endsWith("/")) result += "/"
    return result
}

fun HttpServletRequest.getIP(): String {
    // X-Forwarded-For：Squid 服务代理
    var ipAddresses = this.getHeader("X-Forwarded-For")
    // Proxy-Client-IP：apache 服务代理
    if (ipAddresses.isNullOrBlank() || "unknown".equals(ipAddresses, ignoreCase = true)) ipAddresses = this.getHeader("Proxy-Client-IP")
    // WL-Proxy-Client-IP：weblogic 服务代理
    if (ipAddresses.isNullOrBlank() || "unknown".equals(ipAddresses, ignoreCase = true)) ipAddresses = this.getHeader("WL-Proxy-Client-IP")
    // HTTP_CLIENT_IP：有些代理服务器
    if (ipAddresses.isNullOrBlank() || "unknown".equals(ipAddresses, ignoreCase = true)) ipAddresses = this.getHeader("HTTP_CLIENT_IP")
    // X-Real-IP：nginx服务代理
    if (ipAddresses.isNullOrBlank() || "unknown".equals(ipAddresses, ignoreCase = true)) ipAddresses = this.getHeader("X-Real-IP")
    // 有些网络通过多层代理，那么获取到的ip就会有多个，一般都是通过逗号（,）分割开来，并且第一个ip为客户端的真实IP
    val result = if (ipAddresses.isNotNullOrBlank() && !"unknown".equals(ipAddresses, ignoreCase = true)) ipAddresses.split(",").toTypedArray()[0]
    else this.remoteAddr
    return if (result == "0:0:0:0:0:0:0:1") "127.0.0.1" else result
}